<template>
  <div id="main" />
</template>

<script>
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { BarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer
])

export default {
  name: 'IncomeChart',
  props: {
    incomeData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      echartsInstance: null

    }
  },
  mounted() {
    // 生成echarts
    this.echartsInit()
    // 监听窗口尺寸变化，重置echarts尺寸
    window.addEventListener('resize', () => {
      // 添加防抖
      if (!this.timer) {
        this.timer = setTimeout(() => {
          this.echartsInstance.resize()
          this.timer = null
        }, 500)
      }
    })
  },
  destroyed() {
    // 销毁echarts
    this.echartsInstance.dispose()
  },
  methods: {
    // 生成echarts
    echartsInit() {
      var chartDom = document.getElementById('main')
      this.echartsInstance = echarts.init(chartDom)
      this.echartsInstance.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return params[0].name + '<br/>' +
              '总收入：' + (params[0].value + params[1].value) + ' 元' + '<br/>' +
              params[0].seriesName + '：' + params[0].value + ' 元' + '<br/>' +
              params[1].seriesName + '：' + params[1].value + ' 元'
          },
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['园区收入', '行车收入'],
          right: 20,
          orient: 'vertical'
        },
        xAxis: {
          type: 'category',
          name: '月份',
          data: this.incomeData.xmonth
        },
        yAxis: {
          type: 'value',
          name: '金额',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        series: [
          {
            name: '园区收入',
            type: 'bar',
            data: this.incomeData.ybuilding,
            stack: '收入',
            itemStyle: {
              color: '#0055ff'
            }
          },
          {
            name: '行车收入',
            type: 'bar',
            data: this.incomeData.yparking,
            stack: '收入',
            barWidth: '30%',
            itemStyle: {
              color: '#aec6ff'
            }
          }
        ]
      })
    }
  }
}
</script>

<style scoped lang="scss">
#main {
  width: 100%;
  height: 300px;
}
</style>
